#! /usr/bin/python3

import http.client
import json
import threading
import queue


class Zoom:
    def __init__(self, userid, auth, channel=None, contact=None):
        self.msgId = None
        self.uri = '/v2/chat/users/' + userid + '/messages'
        self.channel = channel
        self.contact = contact
        self.headers = {
            'content-type': "application/json",
            'authorization': "Bearer "+auth
        }
        self.msgs = queue.Queue(100)
        self.seg_id = None
        self.msg_id = None

    def make_msg(self, msg):
        if self.channel:
            return '{"message": "'+msg + '", "to_channel": "'+self.channel + '"}'
        if self.contact:
            return '{"message": "'+msg + '", "to_contact": "'+self.contact + '"}'
        return ""

    def run(self):
        def auto_send():
            msg = self.msgs.get(block=True, timeout=10)
            print('zoom.send: ', msg)
            uri = self.uri
            if self.seg_id == msg[0]:
                uri = uri + '/' + self.msg_id

            try:
                con = http.client.HTTPSConnection("api.zoom.us")
                con.request("POST", uri, self.make_msg(
                    msg[1]).encode('utf-8'), self.headers)
                res = con.getresponse()
                rep = res.read().decode('utf-8')
                print('zoom.recv: ', rep)
                if self.seg_id != msg[0]:
                    self.msg_id = json.loads(rep)["id"]
            except:
                print('zomm.error!')

        thr = threading.Thread(target=auto_send)
        thr.start()

    def on_forward(self, id, a, b):
        xmsg = '>{}\n<{}'.format(a, b)
        self.msgs.put((id, xmsg))
        print(id)
        print(xmsg)
